package com.zzh.bc.utils;

import com.google.gson.Gson;
import com.zzh.bc.log.log;
import com.zzh.bc.vo.BaseRespVo;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;

/**
 * 响应返回的参数
 */
public class RespParamUtils {

    private static final Gson mGson;

    static {
        mGson = new Gson();
    }

    /**
     * 响应成功
     *
     * @param resp 响应实例
     * @param data 响应数据
     */
    public static void respJsonOk(HttpServletResponse resp, Object data) {
        if (resp == null) {
            throw new NullPointerException(" HttpServletResponse is not be null");
        }
        PrintWriter outputStream = null;
        try {
            resp.setContentType("application/json;charset=UTF-8");
            outputStream = resp.getWriter();
            String json = mGson.toJson(BaseRespVo.respResultOK(data));
            log.d("---响应数据json： " + json);
            outputStream.println(json);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeResp(outputStream);
        }
        return;
    }

    /**
     * 响应失败
     *
     * @param resp 响应实例
     */
    public static void respJsonError(HttpServletResponse resp, String error) {
        if (resp == null) {
            throw new NullPointerException(" HttpServletResponse is not be null");
        }
        PrintWriter sos = null;
        try {
            resp.setContentType("application/json;charset=UTF-8");
            sos = resp.getWriter();
            String s = mGson.toJson(BaseRespVo.respResultError(error));
            log.d("---响应数据json： " + s);
            sos.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeResp(sos);
        }
        return;
    }

    private static void closeResp(PrintWriter sos) {
        if (sos != null) {
            sos.close();
        }
    }

    /**
     * 响应失败
     *
     * @param resp 响应实例
     */
    public static void respJsonError(HttpServletResponse resp) {
        if (resp == null) {
            throw new NullPointerException(" HttpServletResponse is not be null");
        }
        PrintWriter outputStream = null;
        try {
            resp.setContentType("application/json;charset=UTF-8");
            outputStream = resp.getWriter();
            String json = mGson.toJson(BaseRespVo.respResultError());
            log.d("---响应数据json： " + json);
            outputStream.println(json);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeResp(outputStream);
        }
        return;
    }

}
